package com.link4a.doms.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.link4a.doms.Constants;
import com.link4a.doms.exception.ValidationException;
import com.link4a.doms.model.User;
import com.link4a.doms.service.UserService;
import com.link4a.doms.vo.UserCondition;
import com.link4a.doms.web.ControllerSupport;
import com.link4a.doms.web.JsonResult;
import com.link4a.doms.web.auth.Auth;
import com.link4a.doms.web.auth.Privilege;

/**
 * @author brown
 */
@Controller
@RequestMapping("user")
public class UserController extends ControllerSupport {

	@Autowired
	private UserService userService;

	@RequestMapping
	@ResponseBody
	public JsonResult findPage(@RequestBody UserCondition condition) {
		return success(userService.findPage(condition));
	}

	@RequestMapping("/get/{username}")
	@ResponseBody
	public JsonResult findByUsername(@PathVariable String username) {
		return success(userService.findByUsername(username));
	}

	@RequestMapping
	@ResponseBody
	public JsonResult currUser(@Auth User user) {
		return success(user);
	}

	@RequestMapping(value="/delete/{username}", method = RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.USER_CUD)
	public JsonResult delete(@PathVariable String username) {
		userService.delete(username);
		return success();
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	@Privilege(Constants.USER_CUD)
	public JsonResult create(@RequestBody User user) {
		try {
			userService.create(user);
			return success();
		} catch (ValidationException e) {
			return result(e.getCode());
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public JsonResult update(@RequestBody User user) {
		userService.update(user);
		return success();
	}

	@RequestMapping
	public ModelAndView profile() {
		ModelAndView mav = new ModelAndView("/system/profile");
		return mav;
	}

	@RequestMapping
	@Privilege(Constants.USER_INDEX)
	public ModelAndView index() {
		ModelAndView mav = new ModelAndView("/system/user");
		return mav;
	}

	@RequestMapping
	@Privilege(Constants.USER_CUD)
	public ModelAndView add() {
		ModelAndView mav = new ModelAndView("/system/userAdd");
		return mav;
	}

	@RequestMapping(value = "/edit/{username}")
	@Privilege(Constants.USER_CUD)
	public ModelAndView edit(@PathVariable String username) {
		ModelAndView mav = new ModelAndView("/system/userAdd");
		mav.addObject("username", username);
		return mav;
	}
}
